<template>
  <div class="app-container">
    <!--查询-->
    <el-form :inline="true" :model="appraiseQuery" class="demo-form-inline">
      <el-form-item label="名字">
        <el-select v-model="appraiseQuery.userId" filterable clearable placeholder="输入名字">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考评结果">
        <el-select v-model="appraiseQuery.result" style="margin-left: 10px;width: 80%" clearable placeholder="可搜索">
          <el-option
            v-for="status in appraiseResultEnum"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="appraiseQuery.status" style="margin-left: 10px;width: 80%" clearable placeholder="可搜索">
          <el-option
            v-for="status in statusEnum"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="handleAddAppraise">创建考评</el-button>

    <el-table :data="appraiseList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="名字">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="appraiseDate" label="考评日期">
        <template slot-scope="scope">
          <el-date-picker readonly v-model="scope.row.appraiseDate" type="date" placeholder="考评日期"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="content" label="考评文件">
        <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="downloadFile(scope.row.content)">
              下载
            </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="remark" label="备注">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="remark" label="结果">
        <template slot-scope="scope">
          <el-select v-model="scope.row.result" disabled style="margin-left: 10px;width: 80%" placeholder="结果">
            <el-option
              v-for="status in appraiseResultEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="remark" label="状态">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" disabled style="margin-left: 10px;width: 80%" placeholder="状态">
            <el-option
              v-for="status in statusEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)"
                     :disabled="scope.row.status==='FALSE'">考评</el-button>
          <el-button type="primary" size="small" @click="addAdjustSalary(scope)"
                     :disabled="scope.row.result==='OTHER'||scope.row.status==='FALSE'">调薪</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getAppraises"
      />
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Appraise':'New Appraise'">
      <el-form :model="appraise" label-width="80px" label-position="left">
        <el-form-item label="考评人员" v-if="dialogType==='new'">
          <el-select v-model="userIds" filterable multiple placeholder="输入名字">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考评日期">
          <el-date-picker
            v-model="appraise.appraiseDate"
            type="date"
            value-format="timestamp"
            placeholder="时间点">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考评文件">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            accept="image/jpeg,image/jpg,image/png,pdf"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :http-request="upload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="appraise.remark" placeholder="备注"/>
        </el-form-item>
        <el-form-item label="考评结果" v-if="dialogType==='edit'">
          <el-select v-model="appraise.result" style="width: 80%" placeholder="请选择">
            <el-option
              v-for="status in appraiseResultEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAppraise">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="adjustDialogVisible" title="添加调薪">
      <el-form :model="adjustSalary" label-width="80px" label-position="left">
        <el-form-item label="调薪人员">
          {{ adjustSalary.name }}
        </el-form-item>
        <el-form-item label="调薪日期">
          <el-date-picker
            v-model="adjustSalary.changeDate"
            type="date"
            value-format="timestamp"
            placeholder="时间点">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上涨幅度">
          <el-input v-model="adjustSalary.percentage" placeholder="上涨幅度(如:25)"/>
        </el-form-item>
        <el-form-item label="原因">
          <el-input v-model="adjustSalary.reason" placeholder="原因"/>
        </el-form-item>
        <el-form-item label="备注" v-if="dialogType==='edit'">
          <el-input v-model="adjustSalary.remark" placeholder="备注"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="adjustDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAdjust">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { batchAddAppraise, getAppraises, modifyAppraise } from '@/api/appraise'
import { deepClone } from '@/utils'
import { getUserList } from '@/api/user'
import { addAdjustSalary } from '@/api/adjustSalary'
import { download, upload } from '@/api/file'

const defaultAppraise = {
  id: ''
}
const defaultAdjust = {

}

export default {
  name: 'AppraiseManager',
  components: {},
  data() {
    return {
      appraise: Object.assign({}, defaultAppraise),
      adjustSalary: Object.assign({}, defaultAdjust),
      appraiseList: [],
      userList: [],
      userIds: [],
      fileList: [],
      appraiseQuery: {},
      statusEnum: [
        {value: 'FALSE', label: "已生效"},
        {value: 'TRUE', label: "未生效"},
      ],
      appraiseResultEnum: [
        {value: 'A', label: "优秀"},
        {value: 'B', label: "良好"},
        {value: 'C', label: "及格"},
        {value: 'D', label: "不及格"},
        {value: 'OTHER', label: "待审核"},
      ],
      checkStrictly: false,
      total: 100,
      page: 1,
      limit: 20,
      dialogType: 'new',
      dialogVisible: false,
      adjustDialogVisible: false,
    };
  },
  //方法集合
  methods: {
    async getAppraises(page = 1){
      const offset = this.limit * (page - 1);
      const res = await getAppraises(this.appraiseQuery, offset, this.limit)
      this.appraiseList = res.data.rows
      this.total = res.data.total
    },
    onSubmit() {
      this.getAppraises()
    },
    async getUserList() {
      const res = await getUserList()
      this.userList = res.data
    },
    handleAddAppraise() {
      this.userIds = []
      this.appraise = Object.assign({}, defaultAppraise)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.appraise = deepClone(scope.row)
      this.$nextTick(() => {
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
      })
    },
    addAdjustSalary(scope) {
      this.adjustDialogVisible = true
      this.adjustSalary = Object.assign({}, defaultAdjust)
      this.adjustSalary.name = scope.row.name
      this.adjustSalary.userId = scope.row.userId
      this.adjustSalary.appraiseId = scope.row.id
    },
    async confirmAdjust() {
      await addAdjustSalary(this.adjustSalary)
      this.adjustDialogVisible = false
      await this.getAppraises()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '操作成功',
        type: 'success'
      })
    },
    async confirmAppraise() {
      if ('edit' === this.dialogType) {
        await modifyAppraise(this.appraise.id, this.appraise)
        for (let index = 0; index < this.appraiseList.length; index++) {
          if (this.appraiseList[index].id === this.appraise.id) {
            this.appraiseList.splice(index, 1, Object.assign({}, this.appraise))
            break
          }
        }
      } else {
        const length = this.userIds.length
        this.appraise.userIds = this.userIds.slice(0, length)
        await batchAddAppraise(this.appraise)
      }
      this.dialogVisible = false
      await this.getAppraises()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '操作成功',
        type: 'success'
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.appraise.content = ''
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    async upload(params) {
      let form = new FormData();
      this.$refs.upload.uploadFiles.forEach((file) => {
        form.append("file", file.raw);
      });
      await upload(form).then((res) => {
        this.appraise.content = res.data
        // console.log(this.contract.fileId)
      })
    },
    async downloadFile(fileName) {
      await download(fileName).then(res => {           //定义文件名等相关信息
        const blob = res
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getAppraises()
    this.getUserList()
  }
}

</script>

<style scoped>
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
